<?php


namespace api\controllers;


use api\components\BaseController;
use common\cache\DictCache;
use common\helpers\commonApi;
use common\helpers\PageApi;
use common\helpers\TransformApi;
use common\models\Activity;
use common\models\ActivityClassify;
use common\models\ActivityEnter;
use common\models\ActivityEvaluate;
use common\models\ActivityLike;
use common\models\System;
use common\models\User;
use Yii;

class ActivityController extends BaseController
{
    /**
     * 公共参数
     * @return array
     */
    public function actionCommon()
    {
        $classify = ActivityClassify::find()
            ->select(['id as value','name'])
            ->where(['status'=>1,'p_id'=>0])
            ->orderBy(['p_id'=>SORT_ASC,'sort'=>SORT_DESC,'create_time'=>SORT_DESC])
            ->asArray()
            ->all();
        array_unshift($classify,['value'=>'','name'=>'全部']);
//        $arr = [0=>['a_id'=>0,'name'=>'全部','sons'=>[]]];
//        foreach ($classify as $value){
//            if (!$value['p_id']){
//                $arr[$value['id']] = [
//                    'a_id'=>$value['id'],
//                    'name'=>$value['name'],
//                    'sons'=>[['s_id'=>0,'name'=>'全部']],
//                ];
//            }else{
//                $arr[$value['p_id']]['sons'] = ['s_id'=>0,'name'=>$value['name']];
//            }
//        }
        //分类
//        $classifyArr = array_values($arr);
        //时段
        $period = DictCache::get('sys_activity_period');
        $periodArr = [['value'=>'','name'=>'全部']];
        foreach ($period as $k=>$per){
            $periodArr[] = ['value'=>$k,'name'=>$per];
        }
        //状态
        $statusAll = [['value'=>'','name'=>'全部']];
        $status = DictCache::get('sys_activity_status');
        foreach ($status as $kk=>$st){
            $statusAll[] = ['value'=>$kk,'name'=>$st];
        }
        $activity = Activity::find()->where(['status'=>1])->groupBy(['city'])->select(['city'])->asArray()->all();
        $cityArr = [['value'=>'','name'=>'全部']];
        foreach ($activity as $act){
            $cityArr[] = ['value'=>$act['city'],'name'=>$act['city']];
        }
        return commonApi::message('成功',true,['classify'=>$classify,'period'=>$periodArr,'status'=>$statusAll,'city'=>$cityArr]);
    }

    /**
     * 列表
     * @return array
     */
    public function actionList()
    {
        $get = Yii::$app->request->get();
        $page = (int)$get['page']??1;
        $a_id = $get['a_id']??'';
        $period = $get['period']??'';
        $status = $get['status']??'';
        $city = $get['city']??'';
        $keyword = $get['keyword']??'';
        $query = Activity::find()->where(['status'=>1,'delete'=>0])->select([
            'id as act_id','main_img','name','total','surplus','start_time','end_time','price'
        ])->andWhere(['delete'=>0])->orderBy(['is_recommend'=>SORT_DESC,'sort'=>SORT_DESC,'create_time'=>SORT_DESC]);
        //时段
        $start_time = '';
        $end_time = '';
        switch ($period){
            case 'today';//今天
                $start_time = date('Y-m-d');
                $end_time = date('Y-m-d 23:59:59');
                break;
            case 'this_week'://	本周
                $w = date('w');
                $start_time = date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')-$w+1,date('Y')));
                $end_time = date('Y-m-d 23:59:59',mktime(0,0,0,date('m'),date('d')+(7-$w),date('Y')));
                break;
            case 'this_month'://本月
                $start_time = date('Y-m-01');
                $end_time = date('Y-m-t 23:59:59');
                break;
            case 'three_months':
                $start_time = date('Y-m-d',strtotime("-3 month"));
                $end_time = date('Y-m-d 23:59:59');
                break;
        }
        if ($a_id){
            $query->andWhere(['c_id'=>$a_id]);
        }
        if ($city){
            $query->andWhere(['city'=>$city]);
        }
        if ($keyword){
            $query->andWhere(['like','name',$keyword]);
        }
        $newTime = date('Y-m-d H:i:s');
        switch ($status){
            case 'ing':
                $query->andWhere(['and',['<=','start_time',$newTime],['>','end_time',$newTime]]);
                break;
            case 'end':
                $query->andWhere(['and',['<','end_time',$newTime]]);
                break;
        }
        if ($start_time&&$end_time){
            $query->andWhere(['and',['<=','start_time',$start_time],['>','end_time',$end_time]]);
        }
        $data = PageApi::apiPage($query,$page);
        $act_ids = array_column($data['data'],'act_id');
        $enter = ActivityEnter::find()->where(['act_id'=>$act_ids,'status'=>1])->select(['act_id','sum(num) as num'])->groupBy(['act_id'])->asArray()->all();
        $enter = array_column($enter,'num','act_id');
        $activity_discount = System::getModel()->activity_discount??0;
        foreach ($data['data'] as &$datum){
            $y = $enter[$datum['act_id']]??0;
            $datum['surplus'] = $datum['total']-$y;
            $datum['main_img'] = commonApi::getDomain($datum['main_img']);
            $datum['start_time'] = date('Y-m-d',strtotime($datum['start_time']));
            $datum['end_time'] = date('Y-m-d',strtotime($datum['end_time']));
            $datum['vip_price'] = $datum['price'];
            if ($activity_discount>0){
                $datum['vip_price'] = $datum['price']*($activity_discount/10);
                $datum['vip_price'] = TransformApi::decimalPoint($datum['vip_price']);
            }
            $datum['registered'] = $datum['total']-$datum['surplus'];
        }
        return commonApi::message('成功',true,$data);
    }

    /**
     * 详情
     * @return array
     */
    public function actionDetails()
    {
        $act_id = Yii::$app->request->get('act_id','');
        if (!$act_id){
            return commonApi::message('请选择活动！',false);
        }
        $model = Activity::find()
            ->where(['id'=>$act_id])
            ->one();
        if (!$model){
            return commonApi::message('活动已下架',false);
        }
        $num = ActivityEnter::find()->where(['act_id'=>$act_id,'status'=>1])->sum('num');
        $num = $num??0;
        $model->surplus = $model->total-$num;
        $userid = self::$userid;
        $y_total = $model->total-$model->surplus;
        $info = $model->toArray();
        $info['img'] = commonApi::getDomain($info['img']);
        $activity_discount = System::getModel()->activity_discount??0;
        if ($activity_discount>0){
            $huiyuan = (new User())->isHuiyuan($userid,'','',0);
            if ($huiyuan){
                $info['price'] = $info['price']*($activity_discount/10);
                $info['price'] = TransformApi::decimalPoint($info['price']);
            }
        }
        $userid = self::$userid;
        $isEnter = (new Activity())->isEnter($userid,$act_id,$info['start_time'],$info['end_time'],$info['status'],$info['delete'],$info['surplus']);
        $data = [
            'act_id'=>$info['id'],
            'name'=>$info['name'],
            'views'=>$info['views'],
            'price'=>$info['price'],
            'total'=>$info['total'],
            'surplus'=>$info['surplus'],
            'registered'=>$y_total,
            'details'=>$info['details'],
            'img'=>$info['img'],
            'mobile'=>$info['mobile'],
            'start_time'=>date('Y-m-d',strtotime($info['start_time'])),
            'end_time'=>date('Y-m-d',strtotime($info['end_time'])),
            'status'=>$isEnter['status'],
            'status_title'=>$isEnter['status_title'],
        ];
        $model->views += 1;
        $model->save();
        return commonApi::message('成功',true,$data);
    }

    /**
     * 评价
     * @return array
     */
    public function actionEvaluate()
    {
        $post = Yii::$app->request->post();
        $act_id = $post['act_id']??"";
        $content = $post['content']??"";
        $userid = self::$userid;
        if (!$act_id){
            return commonApi::message('请选择活动！',false);
        }
        if (!$content){
            return commonApi::message('请输入评价内容！',false);
        }
        $activity = Activity::find()->where(['id'=>$act_id,'status'=>1])->one();
        if (!$activity){
            return commonApi::message('活动已下架',false);
        }
        $exists = ActivityEvaluate::find()->where(['act_id'=>$act_id,'userid'=>$userid])->exists();
        if ($exists){
            return commonApi::message('已评价',false);
        }
        $model = new ActivityEvaluate();
        $model->act_id = $act_id;
        $model->userid = $userid;
        $model->content = $content;
        $model->info = json_encode($activity->toArray());
        $model->status = 1;
        $activity_evaluate = System::getModel()->activity_evaluate;
        if ($activity_evaluate){
            $model->review_status = 0;
            $msg = '评价成功，等待审核...';
        }else{
            $model->review_status = 1;
            $model->review_time = date('Y-m-d H:i:s');
            $msg = '评价成功';
        }
        if ($model->save()){
            return commonApi::message($msg);
        }
        $msg = commonApi::getModelError($model);
        return commonApi::message($msg,false);
    }

    /**
     * 点赞
     * @return array
     * @throws \yii\db\StaleObjectException
     */
    public function actionLike()
    {
        $act_id = (int)Yii::$app->request->get('act_id','');
        if (!$act_id){
            return commonApi::message('请选择活动！',false);
        }
        $activity = Activity::find()->where(['id'=>$act_id,'status'=>1])->one();
        if (!$activity){
            return commonApi::message('活动已下架',false);
        }
        $userid = self::$userid;
        $lod = ActivityLike::find()->where(['act_id'=>$act_id,'userid'=>$userid])->one();
        if ($lod){
            $res = $lod->delete();
            if ($res){
                $activity->likes_num -= 1;
                $activity->save();
                return commonApi::message('取消成功');
            }
            return commonApi::message('取消失败！',false);
        }
        $info = User::find()->where(['id'=>$userid])->select(['info'])->scalar();
        $activity->likes_num += 1;
        $model = new ActivityLike();
        $model->act_id = $act_id;
        $model->userid = $userid;
        $model->info = $info;
        if ($model->save()){
            return commonApi::message('点赞成功');
        }
        return commonApi::message(commonApi::getModelError($model));
    }

    /**
     * 获取评价
     * @return array
     */
    public function actionGetEvaluate()
    {
        $get = Yii::$app->request->get();
        $page = (int)$get['page']??1;
        $act_id = (int)$get['act_id']??'';
        if (!$act_id){
            return commonApi::message('请选择活动！',false);
        }
        $query = ActivityEvaluate::find()
            ->select(['content','create_time','userid'])
            ->where(['act_id'=>$act_id,'status'=>1,'review_status'=>1])
            ->orderBy(['create_time'=>SORT_DESC]);

        $data = PageApi::apiPage($query,$page);
        $userids = array_unique(array_column($data['data'],'userid'));
        $user = User::find()->where(['id'=>$userids])->select(['id','info'])->asArray()->all();
        $user = array_column($user,'info','id');
        foreach ($data['data'] as &$datum){
            $info = json_decode($user[$datum['userid']],true);
            $datum['nickname'] = $info['nickName']??'';
            $datum['headimgurl'] = $info['avatarUrl']??'';
            $datum['create_time'] = date('Y.m.d H:i',strtotime($datum['create_time']));
        }
        return commonApi::message('成功',true,$data);
    }

    /**
     * 报名
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function actionEnter()
    {
        $post = Yii::$app->request->post();
        $act_id = (int)$post['act_id']??'';
        $num = (int)$post['num']??0;
        if (!$act_id){
            return commonApi::message('请选择活动！',false);
        }
        if ($num<=0){
            return commonApi::message('数量必须大于0',false);
        }
        return (new ActivityEnter())->enter(self::$userid,$act_id,$num);
    }

    /**
     * 获取点赞
     * @return array
     */
    public function actionGetLike()
    {
        $get = Yii::$app->request->get();
        $page = (int)$get['page']??1;
        $act_id = (int)$get['act_id']??'';
        if (!$act_id){
            return commonApi::message('请选择活动！',false);
        }
        $query = ActivityLike::find()->where(['act_id'=>$act_id])->select(['info','create_time']);
        $data = PageApi::apiPage($query,$page);
        $arr = [];
        foreach ($data['data'] as $datum){
            $info = json_decode($datum['info'],true);
            $one['nickname'] = $info['nickName']??'';
            $one['headimgurl'] = $info['avatarUrl']??'';
            $one['create_time'] = date('Y.m.d H:i',strtotime($datum['create_time']));
            $arr[] = $one;
        }
        return commonApi::message('成功',true,$arr);
    }
}